import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EdubaseSchoolYearGradeApi } from '#/api/edu/base/setting/schoolYearGrade';
import type { DescriptionItemSchema } from '#/components/description';

import { h } from 'vue';

import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';

import { Typography } from 'ant-design-vue';

import { getSchoolPageSimple } from '#/api/edu/base/school';
import { checkOrg } from '#/api/edu/base/schoolTeachingUnit';
import { getAcademicYearPage } from '#/api/edu/base/setting/academicYear';
import { getDeptListCondition } from '#/api/system/dept';
import { getAdminUserPageSimplePermission } from '#/api/system/user';
import { DictTag } from '#/components/dict-tag';
import { getRangePickerDefaultProps } from '#/utils';

const { Paragraph } = Typography;
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'campusDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'periodDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCampus',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCollege',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showDepartment',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showFaculty',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showGroup',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'isSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      rules: 'required',
      dependencies: {
        triggerFields: ['isSchool'],
        show: (values) => !values.isSchool,
        componentProps(values) {
          return {
            async api() {
              const data = await getDeptListCondition({ type: 'area' });
              return handleTree(data);
            },
            key: values.isSchool || 0,
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择行政区划',
            treeDefaultExpandAll: true,
            allowClear: true,
          };
        },
      },
    },
    {
      fieldName: 'schoolId',
      label: '所属学校',
      component: 'ApiPagingSelect',
      rules: 'required',
      dependencies: {
        triggerFields: ['showSchool', 'areaCode'],
        show: (values) => values.showSchool,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode + values.showSchool || 0,
            async api() {
              return await getSchoolPageSimple(
                {
                  status: 1,
                  schoolCampusType: 0,
                  areaCode: values.areaCode,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'schoolName',
            valueField: 'id',
            placeholder: '请选择学校',
            onChange: async (val, option: any) => {
              if (val) {
                const res = await checkOrg(val);
                values.showCampus = res.showCampus;
                values.showCollege = res.showCollege;
                values.showDepartment = res.showDepartment;
                values.showFaculty = res.showFaculty;
                values.showGroup = res.showGroup;
                values.campusDictList = res.showCampus
                  ? res.children || []
                  : [];
                values.periodDictList = res.periodList || [];
              } else {
                values.showCampus = false;
                values.showCollege = false;
                values.showDepartment = false;
                values.showFaculty = false;
                values.showGroup = false;
                values.campusDictList = [];
                values.campusId = undefined;
                values.periodDictList = [];
              }
            },
          };
        },
      },
    },
    {
      fieldName: 'campusId',
      label: '所属校区',
      component: 'Select',
      rules: 'required',
      dependencies: {
        triggerFields: ['showCampus', 'campusDictList'],
        show: (values) => values.showCampus,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.showCampus || false,
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            options: values.campusDictList || [],
            placeholder: '请选择校区',
            onChange: async (val, option: any) => {
              values.periodDictList = val ? option.periodList || [] : [];
            },
          };
        },
      },
    },
    {
      fieldName: 'academicYear',
      label: '学年',
      component: 'ApiPagingSelect',
      rules: 'required',
      componentProps(values) {
        return {
          allowClear: true,
          async api() {
            return await getAcademicYearPage(
              { status: 1, pageNo: 1, pageSize: 20 },
              false,
              false,
            );
          },
          labelField: 'academicName',
          valueField: 'academicYear',
          placeholder: '请选择学年',
        };
      },
    },
    {
      fieldName: 'period',
      label: '所属学段',
      component: 'Select',
      rules: 'required',
      componentProps(values) {
        return {
          allowClear: true,
          options: getDictOptions(DICT_TYPE.EDU_PERIOD, 'number').filter(
            (item) =>
              !values.periodDictList ||
              values.periodDictList.length <= 0 ||
              values.periodDictList.includes(item.value),
          ),
          placeholder: '请选择学段',
        };
      },
    },
    {
      fieldName: 'gradeCode',
      label: '年级',
      rules: 'required',
      component: 'Select',
      dependencies: {
        triggerFields: ['period'],
        componentProps(values) {
          return {
            key: values.period || '99',
            allowClear: true,
            options: getDictOptions(DICT_TYPE.EDU_GRADE, 'number').filter(
              (item) => {
                if (values.period === null || values.period === undefined) {
                  return true;
                }
                let val = values.period.toString();
                if (val === '5') {
                  val = '4';
                }
                if (val === '6') {
                  val = '7';
                }
                return item.parentValue === val;
              },
            ),
            placeholder: '请选择年级',
            onChange: (val, option: any) => {
              if (val) {
                values.gradeAlias = option.label;
                values.gradeName = option.label;
              } else {
                values.gradeAlias = '';
                values.gradeName = '';
              }
            },
          };
        },
      },
    },

    {
      fieldName: 'gradeAlias',
      label: '年级别名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入年度年级别名（如：2024级一年级、2025届高三）',
      },
    },
    {
      fieldName: 'classCount',
      label: '开设的班级数量',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入该年度该年级开设的班级数量（默认0）',
      },
    },

    {
      fieldName: 'headUserId',
      label: '年级组长',
      component: 'ApiPagingSelect',
      componentProps(values) {
        return {
          api: getAdminUserPageSimplePermission,
          labelField: 'text',
          valueField: 'id',
          placeholder: '请选择年级组长',
          onChange: (val, option: any) => {
            if (val) {
              values.headTeacherName = option.fullName || option.nickname;
            }
          },
        };
      },
    },
    {
      fieldName: 'headTeacherName',
      label: '年级组长姓名',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'previousGradeId',
      label: '前置年级ID',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入前置年级ID',
      },
    },
    {
      fieldName: 'status',
      label: '是否有效',
      rules: 'required',
      component: 'Select',
      defaultValue: CommonStatusEnum.ENABLE,
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择是否有效',
      },
    },
    {
      fieldName: 'enrollmentYear',
      label: '入学年份',
      component: 'DatePicker',
      componentProps: {
        picker: 'year',
        format: 'YYYY',
        valueFormat: 'YYYY',
      },
    },
    {
      fieldName: 'remarks',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入备注（如：2024级一年级新增2个实验班）',
      },
    },
  ];
}

export function useInitFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'campusDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'periodDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCampus',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCollege',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showDepartment',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showFaculty',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showGroup',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'isSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      rules: 'required',
      dependencies: {
        triggerFields: ['isSchool'],
        show: (values) => !values.isSchool,
        componentProps(values) {
          return {
            async api() {
              const data = await getDeptListCondition({ type: 'area' });
              return handleTree(data);
            },
            key: values.isSchool || 0,
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择行政区划',
            treeDefaultExpandAll: true,
            allowClear: true,
          };
        },
      },
    },
    {
      fieldName: 'schoolId',
      label: '所属学校',
      component: 'ApiPagingSelect',
      rules: 'required',
      dependencies: {
        triggerFields: ['showSchool', 'areaCode'],
        show: (values) => values.showSchool,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode + values.showSchool || 0,
            async api() {
              return await getSchoolPageSimple(
                {
                  status: 1,
                  schoolCampusType: 0,
                  areaCode: values.areaCode,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'schoolName',
            valueField: 'id',
            placeholder: '请选择学校',
            onChange: async (val, option: any) => {
              if (val) {
                const res = await checkOrg(val);
                values.showCampus = res.showCampus;
                values.showCollege = res.showCollege;
                values.showDepartment = res.showDepartment;
                values.showFaculty = res.showFaculty;
                values.showGroup = res.showGroup;
                values.campusDictList = res.showCampus
                  ? res.children || []
                  : [];
                values.periodDictList = res.periodList || [];
              } else {
                values.showCampus = false;
                values.showCollege = false;
                values.showDepartment = false;
                values.showFaculty = false;
                values.showGroup = false;
                values.campusDictList = [];
                values.campusId = undefined;
                values.periodDictList = [];
              }
            },
          };
        },
      },
    },
    {
      fieldName: 'campusId',
      label: '所属校区',
      component: 'Select',
      rules: 'required',
      dependencies: {
        triggerFields: ['showCampus', 'campusDictList'],
        show: (values) => values.showCampus,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.showCampus || false,
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            options: values.campusDictList || [],
            placeholder: '请选择校区',
            onChange: async (val, option: any) => {
              values.periodDictList = val ? option.periodList || [] : [];
            },
          };
        },
      },
    },
    {
      fieldName: 'academicYear',
      label: '学年',
      component: 'ApiPagingSelect',
      rules: 'required',
      componentProps(values) {
        return {
          allowClear: true,
          async api() {
            return await getAcademicYearPage(
              { status: 1, pageNo: 1, pageSize: 20 },
              false,
              false,
            );
          },
          labelField: 'academicName',
          valueField: 'academicYear',
          placeholder: '请选择学年',
        };
      },
    },
    {
      fieldName: 'period',
      label: '所属学段',
      component: 'Select',
      rules: 'required',
      componentProps(values) {
        return {
          allowClear: true,
          options: getDictOptions(DICT_TYPE.EDU_PERIOD, 'number').filter(
            (item) =>
              !values.periodDictList ||
              values.periodDictList.length <= 0 ||
              values.periodDictList.includes(item.value),
          ),
          placeholder: '请选择学段',
        };
      },
    },
    {
      fieldName: 'type',
      label: '初始化类型',
      component: 'RadioGroup',
      rules: 'required',
      defaultValue: 1,
      componentProps: {
        options: [
          {
            label: '基于上年度',
            value: 1,
          },
          {
            label: '新初始化',
            value: 2,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'classCount',
      label: '开设的班级数量',
      help: '如果选择基于上年度，该值只作用于新的年级,比如一年级、初一、高一；如果选择新初始化，所有年级的班级数都按该值进行初始化。',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入该年度该年级开设的班级数量（默认0）',
      },
    },
  ];
}

/** 详情页字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      label: '学校名称',
      field: 'campusName',
    },
    {
      label: '学年',
      field: 'academicYear',
    },
    {
      label: '所属学段',
      field: 'period',
      render: (val) => {
        return h(DictTag, {
          type: DICT_TYPE.EDU_PERIOD,
          value: val,
        });
      },
    },
    {
      label: '年级编码',
      field: 'gradeCode',
    },
    {
      label: '年度年级别名',
      field: 'gradeAlias',
    },
    {
      label: '开设的班级数量',
      field: 'classCount',
    },
    {
      label: '年级组长姓名',
      field: 'headTeacherName',
    },
    {
      label: '前置年级ID',
      field: 'previousGradeId',
    },
    {
      label: '是否有效',
      field: 'status',
      render: (val) => {
        return h(DictTag, {
          type: DICT_TYPE.COMMON_STATUS,
          value: val,
        });
      },
    },
    {
      label: '入学年份',
      field: 'enrollmentYear',
    },
    {
      label: '备注',
      field: 'remarks',
      render: (val) =>
        h('div', {
          innerHTML: val,
          class: 'whitespace-pre-wrap text-sm leading-relaxed',
        }),
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'academicYear',
      label: '学年',
      component: 'ApiPagingSelect',
      componentProps(values) {
        return {
          allowClear: true,
          async api() {
            return await getAcademicYearPage(
              { status: 1, pageNo: 1, pageSize: 20 },
              false,
              false,
            );
          },
          labelField: 'academicName',
          valueField: 'academicYear',
          placeholder: '请选择学年',
        };
      },
    },
    {
      fieldName: 'showSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'campusDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCampus',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCollege',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showDepartment',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showFaculty',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showGroup',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'isSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['isSchool'],
        show: (values) => !values.isSchool,
        componentProps(values) {
          return {
            async api() {
              const data = await getDeptListCondition({ type: 'area' });
              return handleTree(data);
            },
            key: values.isSchool || 0,
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择行政区划',
            treeDefaultExpandAll: true,
            allowClear: true,
          };
        },
      },
    },
    {
      fieldName: 'schoolId',
      label: '所属学校',
      component: 'ApiPagingSelect',
      dependencies: {
        triggerFields: ['showSchool', 'areaCode'],
        show: (values) => values.showSchool,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode + values.showSchool || 0,
            async api() {
              return await getSchoolPageSimple(
                {
                  status: 1,
                  schoolCampusType: 0,
                  areaCode: values.areaCode,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'schoolName',
            valueField: 'id',
            placeholder: '请选择学校',
            onChange: async (val, option: any) => {
              if (val) {
                const res = await checkOrg(val);
                values.showCampus = res.showCampus;
                values.showCollege = res.showCollege;
                values.showDepartment = res.showDepartment;
                values.showFaculty = res.showFaculty;
                values.showGroup = res.showGroup;
                values.campusDictList = res.showCampus
                  ? res.children || []
                  : [];
                values.periodDictList = res.periodList || [];
              } else {
                values.showCampus = false;
                values.showCollege = false;
                values.showDepartment = false;
                values.showFaculty = false;
                values.showGroup = false;
                values.campusDictList = [];
                values.campusId = undefined;
                values.periodDictList = [];
              }
            },
          };
        },
      },
    },
    {
      fieldName: 'campusId',
      label: '所属校区',
      component: 'Select',
      dependencies: {
        triggerFields: ['showCampus', 'campusDictList'],
        show: (values) => values.showCampus,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.showCampus || false,
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            options: values.campusDictList || [],
            placeholder: '请选择校区',
            onChange: async (val, option: any) => {
              values.periodDictList = val ? option.periodList || [] : [];
            },
          };
        },
      },
    },
    {
      fieldName: 'period',
      label: '所属学段',
      component: 'Select',
      componentProps(values) {
        return {
          allowClear: true,
          options: getDictOptions(DICT_TYPE.EDU_PERIOD, 'number').filter(
            (item) =>
              !values.periodDictList ||
              values.periodDictList.length <= 0 ||
              values.periodDictList.includes(item.value),
          ),
          placeholder: '请选择学段',
        };
      },
    },
    {
      fieldName: 'gradeCode',
      label: '年级编码',
      component: 'Select',
      dependencies: {
        triggerFields: ['period'],
        componentProps(values) {
          return {
            key: values.period || '99',
            allowClear: true,
            options: getDictOptions(DICT_TYPE.EDU_GRADE, 'number').filter(
              (item) => {
                if (values.period === null || values.period === undefined) {
                  return true;
                }
                let val = values.period.toString();
                if (val === '5') {
                  val = '4';
                }
                if (val === '6') {
                  val = '7';
                }
                return item.parentValue === val;
              },
            ),
            placeholder: '请选择年级',
          };
        },
      },
    },
    {
      fieldName: 'gradeAlias',
      label: '年度年级别名',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入年度年级别名',
      },
    },
    {
      fieldName: 'headUserId',
      label: '年级组长',
      component: 'ApiPagingSelect',
      componentProps(values) {
        return {
          api: getAdminUserPageSimplePermission,
          labelField: 'text',
          valueField: 'id',
          placeholder: '请选择年级组长',
        };
      },
    },
    {
      fieldName: 'status',
      label: '是否有效',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择是否有效',
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<EdubaseSchoolYearGradeApi.SchoolYearGrade>['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '年度年级ID（主键）',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'schoolId',
      title: '学校ID（关联学校表主键）',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'campusId',
      title: '校区id',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'campusName',
      title: '所属学校',
      minWidth: 200,
    },

    {
      field: 'academicYear',
      title: '学年',
      minWidth: 120,
    },
    {
      field: 'period',
      title: '所属学段',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.EDU_PERIOD },
      },
    },
    {
      field: 'gradeCode',
      title: '年级编码',
      minWidth: 120,
    },
    {
      field: 'gradeName',
      title: '年级标准名称',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'gradeAlias',
      title: '年度年级别名',
      minWidth: 120,
    },
    {
      field: 'classCount',
      title: '开设的班级数量',
      minWidth: 120,
    },
    {
      field: 'headUserId',
      title: '年级组长用户id',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'headTeacherId',
      title: '年级组长ID',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'headTeacherName',
      title: '年级组长姓名',
      minWidth: 120,
    },
    {
      field: 'previousGradeId',
      title: '前置年级ID',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'status',
      title: '是否有效',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.COMMON_STATUS },
      },
    },
    {
      field: 'enrollmentYear',
      title: '入学年份',
      minWidth: 120,
    },
    {
      field: 'remarks',
      title: '备注',
      minWidth: 200,
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 160,
      formatter: 'formatDateTime',
    },
    {
      field: 'actions',
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
